package com.txd.mofa.base;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.kongzue.baseframework.BaseActivity;
import com.kongzue.baseframework.util.AppManager;
import com.kongzue.baseframework.util.Preferences;
import com.kongzue.baseokhttp.listener.ResponseInterceptListener;
import com.kongzue.baseokhttp.util.BaseOkHttp;
import com.ninetaildemonfox.zdl.ninetails.map.JSONUtils;
import com.txd.mofa.R;
import com.txd.mofa.http.HttpUtils;
import com.txd.mofa.login.LoginAty;
import com.txd.mofa.net.NetChangeObserver;
import com.txd.mofa.net.NetStateReceiver;
import com.txd.mofa.net.NetUtils;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * 创建人： Nine tails fox
 * 创建时间： 2019/5/6
 * 功能描述：所有activity的基类
 * 联系方式：1037438704@qq.com
 *
 * @author NineTailDemonFox
 */

public abstract class BaseAty extends BaseActivity implements HttpUtils {

    public String token = "";
    public static boolean loginBoolean;
    public View getView;
    protected NetChangeObserver mNetChangeObserver = null;

    public boolean flag = true;


    @Override
    public void initViews() {
        token = Preferences.getInstance().getString(me, "mofa", "token");

        Log.e("token",token);

        if (!isNull(token)) {
            loginBoolean = true;
        } else {
            loginBoolean = false;
        }


        AppManager.getInstance().pushActivity(me);

        setAndroidNativeLightStatusBar(me,false);

        getView = getLayoutInflater().inflate(R.layout.text_null, null);

        intercept();

        // 网络改变的一个回掉类
        mNetChangeObserver = new NetChangeObserver() {
            @Override
            public void onNetConnected(NetUtils.NetType type) {
                flag = true;
                onNetworkConnected(type);
                getView = getLayoutInflater().inflate(R.layout.text_null, null);
            }

            @Override
            public void onNetDisConnect() {


                if (isAllEnable(me)) {
                    flag = true;
                } else if (isWiFiEnable(me)){
                    flag = true;
                }else if (hasSimCard(me)){
                    if (isMobileEnableReflex(me)) {
                        flag = true;
                    }else {
                        flag = false;
                    }
                }else {
                    flag = false;
                }
                    onNetworkDisConnected();
                    getView = getLayoutInflater().inflate(R.layout.text_null1, null);

            }
        };

        //开启广播去监听 网络 改变事件
        NetStateReceiver.registerObserver(mNetChangeObserver);
    }

    public void Huoqu(){
        if (isAllEnable(me)) {
            flag = true;
        } else if (isWiFiEnable(me)){
            flag = true;
        }else if (hasSimCard(me)){
            if (isMobileEnableReflex(me)) {
                flag = true;
            }else {
                flag = false;
            }
        }else {
            flag = false;
        }
    }
    public static boolean hasSimCard(Context context) {
        TelephonyManager telMgr = (TelephonyManager)
                context.getSystemService(Context.TELEPHONY_SERVICE);
        int simState = telMgr.getSimState();
        boolean result = true;
        switch (simState) {
            case TelephonyManager.SIM_STATE_ABSENT:
                result = false; // 没有SIM卡
                break;
            case TelephonyManager.SIM_STATE_UNKNOWN:
                result = false;
                break;
        }
        Log.d("try", result ? "有SIM卡" : "无SIM卡");
        return result;
    }

    public boolean isAllEnable(Context context) {
        return isWiFiEnable(context) && isMobileEnableReflex(context);
    }

    public boolean isWiFiEnable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        }
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        return !((info == null) || (!info.isAvailable())) && info.getType() == ConnectivityManager.TYPE_WIFI;
    }

    public static boolean isMobileEnableReflex(Context context) {
        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            Method getMobileDataEnabledMethod = ConnectivityManager.class.getDeclaredMethod("getMobileDataEnabled");
            getMobileDataEnabledMethod.setAccessible(true);
            return (Boolean) getMobileDataEnabledMethod.invoke(connectivityManager);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }



    /**
     * 网络连接状态
     *
     * @param type 网络状态
     */
    protected abstract void onNetworkConnected(NetUtils.NetType type);


    /**
     * 网络断开的时候调用
     */
    protected abstract void onNetworkDisConnected();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NetStateReceiver.removeRegisterObserver(mNetChangeObserver);
    }



    private static void setAndroidNativeLightStatusBar(Activity activity, boolean dark) {
        View decor = activity.getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }
    @Override
    protected void onResume() {
        super.onResume();

        //友盟
        MobclickAgent.onResume(this);

        token = Preferences.getInstance().getString(me, "mofa", "token");
        if (!isNull(token)) {
            loginBoolean = true;
        } else {
            loginBoolean = false;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this); // 不能遗漏
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public void bottonNavigationBarUtil() {
//        //初始化底部导航栏
//        if (NavigationBarUtil.hasNavigationBar(this)) {
//            NavigationBarUtil.initActivity(findViewById(android.R.id.content));
//        }
    }

    //webveiw
    protected void initWeb(WebSettings webSettings, WebView tvWeb) {
        webSettings.setPluginState(WebSettings.PluginState.ON);

        webSettings.setDomStorageEnabled(true);//设置适应Html5的一些方法
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        // 若加载的 html 里有JS 在执行动画等操作，会造成资源浪费（CPU、电量）
        // 在 onStop 和 onResume 里分别把  setJavaScriptEnabled() 给设置成 false 和 true 即可

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        //其他细节操作
        //        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(false); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setDefaultFontSize((int) 15);
    }

    /**
     * 网络拦截器
     */
    public void intercept() {
        //全局拦截器
        BaseOkHttp.responseInterceptListener = new ResponseInterceptListener() {
            @Override
            public boolean onResponse(Context context, String url, String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);

                    if (map == null) {
                        return false;
                    }
                    if (map.get("code").equals("-1")) {
                        log("==========code========-1====");
                        loginBoolean = false;
                        AppManager.getInstance().killAllActivity();
                        Preferences.getInstance().cleanAll(me,"mofa");
                        jump(LoginAty.class);

                        return false;
                    }
                    if (map.get("code").equals("1")) {
                        log("==========code========1====");
                        return true;
                    }

                    if (map.get("code").equals("0")) {
                        log("==========code========1====");
                        return true;
                    }
                    log("==========code========0====");
                    toast(map.get("message"));
                    return false;
                } else {
                    Log.i("!!!", "onResponse: " + response);
                    return false;
                }
            }
        };
    }
}
